/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.lzx.iteam.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import com.lzx.iteam.R;

/**
 * Create a 4x3 grid of dial buttons.
 *
 * It was easier and more efficient to do it this way than use
 * standard layouts. It's perfectly fine (and actually encouraged) to
 * use custom layouts rather than piling up standard layouts.
 *
 * The horizontal and vertical spacings between buttons are controlled
 * by the amount of padding (attributes on the ButtonGridLayout element):
 *   - horizontal = left + right padding and
 *   - vertical = top + bottom padding.
 *
 * This class assumes that all the buttons have the same size.
 * The buttons will be bottom aligned in their view on layout.
 *
 * Invocation: onMeasure is called first by the framework to know our
 * size. Then onLayout is invoked to layout the buttons.
 */
//: Blindly layout the buttons w/o checking if we overrun the
// bottom-right corner.

public class ButtonGridLayout extends ViewGroup {
    
    private static final String TAG = "ButtonGridLayout";
    private static final boolean DBG = false;
    
    private int num_children;
    private int rows;
    private int columns;

    private View[] mButtons;

    // This what the fields represent (height is similar):
    // PL: mPaddingLeft
    // BW: mButtonWidth
    // PR: mPaddingRight
    //
    //        mWidthInc
    // <-------------------->
    //   PL      BW      PR
    // <----><--------><---->
    //        --------
    //       |        |
    //       | button |
    //       |        |
    //        --------
    //
    // We assume mPaddingLeft == mPaddingRight == 1/2 padding between
    // buttons.
    //
    // mWidth == COLUMNS x mWidthInc

    // Width and height of a button
    private int mButtonWidth;
    private int mButtonHeight;

    private float mGap;
    private Context context;
    
    // Height of the dialpad. Used to align it at the bottom of the
    // view.
    private int mWidth;
    private int mHeight;

    public ButtonGridLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
               this.context = context;
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ButtonGrid);
        
        mGap = a.getDimension(R.styleable.ButtonGrid_gap, 1.0f); // hard code here
        rows = a.getInteger(R.styleable.ButtonGrid_row, 1);
        columns = a.getInteger(R.styleable.ButtonGrid_column, 1);
        
        num_children = rows * columns;
        mButtons = new View[num_children];
        a.recycle();
    }

    public ButtonGridLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * Cache the buttons in a member array for faster access.  Compute
     * the measurements for the width/height of buttons.  The inflate
     * sequence is called right after the constructor and before the
     * measure/layout phase.
     */
    @Override
    protected void onFinishInflate () {
        super.onFinishInflate();
        final View[] buttons = mButtons;
        for (int i = 0; i < num_children; i++) {
            buttons[i] = getChildAt(i);
            // Measure the button to get initialized.
//            buttons[i].measure(MeasureSpec.UNSPECIFIED , MeasureSpec.UNSPECIFIED);
        }

        // Cache the measurements.
//        final View child = buttons[0];
//        mButtonWidth = child.getMeasuredWidth();
//        mButtonHeight = child.getMeasuredHeight();
//        mWidthInc = mButtonWidth + getPaddingLeft() + getPaddingRight();
//        mHeightInc = mButtonHeight + getPaddingTop() + getPaddingBottom();
//        mWidth = COLUMNS * mWidthInc;
//        mHeight = ROWS * mHeightInc;
    }

    /**
     * Set the background of all the children. Typically a selector to
     * change the background based on some combination of the button's
     * attributes (e.g pressed, enabled...)
     * @param resid Is a resource id to be used for each button's background.
     */
    public void setChildrenBackgroundResource(int resid) {
        final View[] buttons = mButtons;
        for (int i = 0; i < num_children; i++) {
            buttons[i].setBackgroundResource(resid);
        }
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        
                /*
         * <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="fill_parent"
                    android:src="@drawable/dial_panel_divider" />
         */
//        ImageView imageView = new ImageView(getContext());
//        imageView.setatt
            // The last row is bottom aligned.
            int width = mWidth = right-left;
            int height = mHeight = bottom-top;
       /* if(height%rows!=0){
            height+=(rows-height%rows);
        }
        if(width%columns!=0){
            width+=(columns-width%columns);
        }
        mHeight = height;
        mWidth = width;*/
            Log.d(TAG, "value: ");
            int y = height - mHeight + getPaddingTop();

            int gapPixel = MeasureSpec.getSize((int) mGap);

            mButtonWidth = (int) (width - getPaddingLeft() - getPaddingRight()
                    - gapPixel * (columns - 1)) / columns;
            mButtonHeight = (int) (height - getPaddingTop() - getPaddingBottom()
                    - gapPixel * (rows - 1)) / rows;

            int btnWidthMeasureSpec = MeasureSpec.makeMeasureSpec(mButtonWidth, MeasureSpec.EXACTLY);
            int btnHeightMeasureSpec = MeasureSpec.makeMeasureSpec(mButtonHeight, MeasureSpec.EXACTLY);

            for (int i = 0; i < num_children; i++) {
                TextImageButton button = (TextImageButton) mButtons[i];
                if (button != null) {
                    button.measure(btnWidthMeasureSpec*button.width, btnHeightMeasureSpec);
                }
            }

        /*int widthSpec = MeasureSpec.makeMeasureSpec(mWidth, MeasureSpec.EXACTLY);
        int heightSpec = MeasureSpec.makeMeasureSpec(mHeight, MeasureSpec.EXACTLY);
        setMeasuredDimension(widthSpec, heightSpec);*/
            int i = 0;
            final View[] buttons = mButtons;
            final int paddingLeft = getPaddingLeft();
            final int buttonWidth = mButtonWidth;
            final int buttonHeight = mButtonHeight;
            for (int row = 0; row < rows; row++) {
                int x = paddingLeft;
                for (int col = 0; col < columns; col++) {
                    TextImageButton button = (TextImageButton) buttons[i];

                    if (button != null) {
                        button.layout(x, y, x + buttonWidth*button.width, y + buttonHeight);
                        x += (buttonWidth + gapPixel);
                        i++;
                    }
                }
                y += (buttonHeight + gapPixel);
            }

    }

    /**
     * This method is called twice in practice. The first time both
     * with and height are constraint by AT_MOST. The second time, the
     * width is still AT_MOST and the height is EXACTLY. Either way
     * the full width/height should be in mWidth and mHeight and we
     * use 'resolveSize' to do the right thing.
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        
        if (DBG) Log.d(TAG, "onMeasure --> widthMeasureSpec: " + MeasureSpec.toString(widthMeasureSpec)
                + " heightMeasureSpec: " + MeasureSpec.toString(heightMeasureSpec));
        
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        
        
      
        
        // we prefer child size measured by parent 
//        width = resolveSize(mWidth, widthMeasureSpec);
//        height = resolveSize(mHeight, heightMeasureSpec);
        
        //setMeasuredDimension(width, height);
    }
    
    public int getColumns(){
        return columns;
    }
    
    public int getRows(){
        return rows;
    }
}


